package com.cp.oss.controller;

import com.cp.common.exception.BusinessException;
import com.cp.common.result.R;
import com.cp.common.result.ResponseEnum;
import com.cp.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author ming
 * @create 2022/8/1
 * @description:
 */
@Api(tags = "阿里云文件上传")
//@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/api/oss/file")
public class FileController {
    @Resource
    private FileService fileService;
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public R  upload(@ApiParam(value = "文件",required = true)
                         @RequestParam("file")MultipartFile file, @ApiParam(value = "模块",required = true)
                         @RequestParam("module")String module) {
        String url = "";
        try {
           url = fileService.fileUpload(file.getInputStream(), module, file.getOriginalFilename());
        } catch (IOException e) {
            log.error("文件上传失败",e.getStackTrace());
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR);
        }
        return R.ok().message("文件上传成功").data("url",url) ;
    }
    @DeleteMapping("/remove")
    @ApiOperation("文件删除")
    public R remove(@ApiParam(value = "要删除的文件",required = true)
                    @RequestParam("url") String  url){
        fileService.removeFile(url);
        return R.ok().message("删除成功!");
    }

}
